"""
通知相关的Celery任务
"""

import asyncio
from typing import Dict, Any

from celery import current_task
from .celery import celery
from services.notification_service import notification_service
from database import AsyncSessionLocal
from utils.logger import get_logger

logger = get_logger(__name__)


@celery.task(bind=True, max_retries=3)
def send_task_notification(self, execution_id: int, event_type: str) -> Dict[str, Any]:
    """
    发送任务通知

    Args:
        execution_id: 执行记录ID
        event_type: 事件类型 (success, failure, started)

    Returns:
        发送结果
    """
    task_id = current_task.request.id

    logger.info(
        "开始发送任务通知",
        execution_id=execution_id,
        event_type=event_type,
        task_id=task_id
    )

    try:
        # 运行异步任务
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        try:
            result = loop.run_until_complete(
                _send_task_notification_async(execution_id, event_type)
            )
            return result
        finally:
            loop.close()

    except Exception as e:
        logger.error(
            "任务通知发送失败",
            execution_id=execution_id,
            event_type=event_type,
            error=str(e)
        )
        raise


async def _send_task_notification_async(execution_id: int, event_type: str) -> Dict[str, Any]:
    """异步发送任务通知"""
    async with AsyncSessionLocal() as db:
        notifications = await notification_service.send_task_notification(
            execution_id=execution_id,
            event_type=event_type,
            db=db
        )

        return {
            "execution_id": execution_id,
            "event_type": event_type,
            "notifications_sent": len(notifications),
            "notification_ids": [n.id for n in notifications]
        }


@celery.task
def test_email_configuration(recipient: str) -> Dict[str, Any]:
    """
    测试邮件配置

    Args:
        recipient: 测试收件人邮箱

    Returns:
        测试结果
    """
    logger.info("开始测试邮件配置", recipient=recipient)

    try:
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        try:
            result = loop.run_until_complete(
                notification_service.test_email_configuration(recipient)
            )
            return result
        finally:
            loop.close()

    except Exception as e:
        logger.error("邮件配置测试失败", recipient=recipient, error=str(e))
        return {
            "success": False,
            "message": f"测试失败: {str(e)}",
            "recipient": recipient
        }


@celery.task
def cleanup_old_notifications():
    """清理过期通知记录"""
    try:
        logger.info("开始清理过期通知记录")

        # TODO: 实现通知记录清理逻辑
        # 例如：删除30天前的已发送通知记录

        logger.info("过期通知记录清理完成")
        return {"status": "success", "message": "通知记录清理完成"}

    except Exception as e:
        logger.error("通知记录清理失败", error=str(e))
        return {"status": "failure", "error": str(e)}